﻿using HaoCoding.DCdb.General.IO;
using HaoCoding.DCdb.WaterfallTree;
using System.Collections.Generic;
using System.IO;

namespace HaoCoding.DCdb.Storage
{
    /// <summary>
    /// 数据堆
    /// </summary>
    public class Heap : IHeap
    {
        /// <summary>
        /// 同步锁
        /// </summary>
        private readonly object SyncRoot = new object();

        /// <summary>
        /// 数据空间
        /// </summary>
        private readonly Space space;

        //handle -> pointer
        private readonly Dictionary<long, Pointer> used;

        /// <summary>
        /// 数据库文件流
        /// </summary>
        public Stream Stream { get; private set; }

        /// <summary>
        /// 实例化数据堆
        /// </summary>
        /// <param name="stream">打开的数据库文件流</param>
        /// <param name="useCompression">是否使用压缩，默认为false</param>
        /// <param name="strategy">自由空间分配策略，默认为从当前块往前搜索</param>
        public Heap(Stream stream, bool useCompression = false, AllocationStrategy strategy = AllocationStrategy.FromTheCurrentBlock)
        {
            stream.Seek(0, SeekOrigin.Begin);  // 设置数据流的开始位置

            Stream = stream;

            space = new Space();
        }

        /// <summary>
        /// 实例化数据堆
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="useCompression">是否使用压缩，默认为false</param>
        /// <param name="strategy">自由空间分配策略，默认为从当前块往前搜索</param>
        public Heap(string fileName, bool useCompression = false, AllocationStrategy strategy = AllocationStrategy.FromTheCurrentBlock)
            : this(new OptimizedFileStream(fileName, FileMode.OpenOrCreate), useCompression, strategy)
        {
        }


        /// <summary>
        /// 关闭文件流并释放文件
        /// </summary>
        public void Close()
        {
            lock (SyncRoot)
                Stream.Close();
        }

    }
}
